﻿#include "server_qt.h"
#include <QTcpSocket>

ServerQt::ServerQt(QObject* parent)
    : QObject(parent) {

}

ServerQt::~ServerQt() {
    qDebug() << "ServerQt::~ServerQt()";
}

void ServerQt::Start() {
    connect(&server_, &QTcpServer::newConnection, this, &ServerQt::OnNewConnection);
    server_.listen(QHostAddress::Any);
    moveToThread(&thread_);
    server_.moveToThread(&thread_);
    thread_.start();
}

void ServerQt::Stop() {
    thread_.exit();
}

void ServerQt::Wait() {
    thread_.wait();
}

unsigned short ServerQt::Port() const{
    return server_.serverPort();
}

void ServerQt::OnNewConnection() {
    auto socket = server_.nextPendingConnection();
    connect(socket, &QTcpSocket::readyRead, this, &ServerQt::OnReadyRead);
    connect(socket, &QTcpSocket::disconnected, socket, &QTcpServer::deleteLater);
}

void ServerQt::OnReadyRead() {
    QTcpSocket* socket = (QTcpSocket*)sender();
    socket->write(socket->readLine().constData());
    socket->flush();
}